package com.sunwhite.herostore.msg.util;

import com.google.protobuf.Message;
import com.sunwhite.herostore.common.GameMsgRecognizer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

/**
 * 编写自定义消息解码器
 */
public class GameMsgDecode extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //不属于websocket不处理
        if (null==msg||!(msg instanceof BinaryWebSocketFrame)){
            return;
        }
        // WebSocket 二进制消息会通过 HttpServerCodec 解码成 BinaryWebSocketFrame 类对象
        BinaryWebSocketFrame webSocketFrame = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = webSocketFrame.content();

        byteBuf.readShort();    //读取消息长度
        short msgCode = byteBuf.readShort();    //读取消息编号


        byte[] msgBody = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(msgBody);     //读取消息体

        //处理protocol的不同消息
       Message.Builder builder= GameMsgRecognizer.getBuilderByMsgCode(msgCode);
        if (builder==null){
            return;
        }
        builder.clear();
        builder.mergeFrom(msgBody);
        Message cmd=builder.build();
        if(null!=cmd){
            ctx.fireChannelRead(cmd);
        }
    }
}
